package com.tokenplus.thai.base

import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModel
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.tokenplus.thai.ProjectConfig
import com.tokenplus.thai.R
import com.tokenplus.thai.components.dialog.LoadingDialog
import com.tokenplus.thai.extend.*
import com.tokenplus.thai.launch.LoginInputMobileActivity
import com.tokenplus.thai.anetwork.NetworkException
import com.tokenplus.thai.utils.analytics.util.AnalyticsUtil
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.annotations.AfterPermissionGranted
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog

const val REQ_GARLICLOAN_CODE_GARLICLOAN_PAGE_GARLICLOAN_PERMISSION: Int = 200
const val KEY_GARLICLOAN_PARAMS_GARLICLOAN_VIRTUAL_GARLICLOAN_BANK_GARLICLOAN_NAME: String =
    "KEY_PARAMS_VIRTUAL_BANK_NAME"
const val KEY_GARLICLOAN_PARAMS_GARLICLOAN_VIRTUAL_GARLICLOAN_BANK_GARLICLOAN_ACCOUNT: String =
    "KEY_PARAMS_VIRTUAL_BANK_ACCOUNT"
const val KEY_GARLICLOAN_PARAMS_GARLICLOAN_REPAY_GARLICLOAN_AMOUNT: String =
    "KEY_PARAMS_VIRTUAL_REPAY_AMOUNT"

abstract class BaseActivity : AppCompatActivity(),
    EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    var ACTIVITY_GARLICLOAN_TAG: String = ""

    private lateinit var mLoadingDialog: LoadingDialog
    private var mPermissionList: Array<String>? = null
    private var mPermissionStatement: String? = null

    private var mSwipeRefresh: SwipeRefreshLayout? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ACTIVITY_GARLICLOAN_TAG = this::class.java.simpleName

        with(window) {
//            requestFeature(Window.FEATURE_CONTENT_TRANSITIONS)
//            exitTransition = Slide(Gravity.START).setDuration(300)
//            enterTransition = Slide(Gravity.END).setDuration(300)
//            exitTransition = Fade()
//            enterTransition = Slide()
        }
        //mFirebaseAnalytics = Firebase.analytics
        setFullScreenMode()
        ACTIVITY_GARLICLOAN_TAG = onBindingViewTag()
        setContentView(onBindingContentView())
//        setContentView(onBindingContentLayoutId())
        mLoadingDialog = LoadingDialog(this)
        setViewModelActions()
        onContentViewBinded()
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view != null) {
                try {
                    if (canHideKeyboard(view, ev)) {
                        hideKeyboard()
                        val editText = view as EditText
                        editText.clearFocus()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return super.dispatchTouchEvent(ev)
        }
        return window.superDispatchTouchEvent(ev) || onTouchEvent(ev)
    }

    override fun onResume() {
        super.onResume()
        val gType =
            "${ProjectConfig.product}_${this.onBindingViewTag()}_START".uppercase()
        AnalyticsUtil.saveHitPointInfo(
            type = gType,
            remark = System.currentTimeMillis().toString()
        )
    }

    override fun onPause() {
        super.onPause()
        val gType =
            "${ProjectConfig.product}_${this.onBindingViewTag()}_END".uppercase()
        AnalyticsUtil.saveHitPointInfo(
            type = gType,
            remark = System.currentTimeMillis().toString()
        )
    }

    open fun savePointEvent(type: String, remark: String = "") {
        try {
            AnalyticsUtil.saveHitPointInfo(
                type = type,
                remark = remark
            )
//            P5bwqcsjj0s2tmsjhwmzg.saveUserBuriedPoint(
//                P2j7zzfx72q29gy4v2nkjja(
//                    type = type,
//                    remark = remark
//                )
//            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**绑定model*/
    protected abstract fun onBindingViewModel(): List<ViewModel>?

    /**绑定tag*/
    protected abstract fun onBindingViewTag(): String

    /**绑定视图开始*/
    protected abstract fun onBindingContentView(): View

    /**绑定视图开始*/
//    protected abstract fun onBindingContentLayoutId(): Int

    /**绑定视图完成*/
    protected abstract fun onContentViewBinded()

    private fun setViewModelActions() {
        val viewModelList = onBindingViewModel()
        if (!(viewModelList.isNullOrEmpty())) {
            viewModelList.forEach {
                if (it is BaseViewModelAction) {
                    it.getLoadingLiveData()
                        .observe(this) { showLoading ->
                            if (showLoading)
                                showLodingDialog()
                            else
                                dismissLoadingDialog()
                        }

                    it.getNetworkExceptionLiveData()
                        .observe(this) {
                            onHandleNetworkExcepton(it)
                        }
                }
            }
        }
    }

    protected fun showLodingDialog() {
        mLoadingDialog.showDialog(this)
    }

    protected fun dismissLoadingDialog() {
        mLoadingDialog.dismissDialog()
    }

    /**交给子类去实现*/
    open fun onHandleNetworkExcepton(networkException: NetworkException) {
        if (networkException.isAlter()) {
//            MessageDialog.showDialog(
//                supportFragmentManager,
//                networkException.msg
//            )
        } else {
            Toast.makeText(this, networkException.msg, Toast.LENGTH_LONG)
                .show()
        }
        if (networkException.msg.contains("User does not exist")) {
            startToNextActivityAndFinish<LoginInputMobileActivity>()
        }
    }

    /**交给子类去实现*/
    open fun onPermissionsRequestAllPass() {

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        mPermissionStatement?.let {
            mPermissionList?.let { list ->
                startEasyPermissions(it, list)
            }
        }
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            mPermissionStatement?.let {
                mPermissionList?.let { list ->
                    startEasyPermissions(it, list)
                }
            }
        }
    }

    @AfterPermissionGranted(REQ_GARLICLOAN_CODE_GARLICLOAN_PAGE_GARLICLOAN_PERMISSION)
    fun onEasyPermissionsAllPass() {
        onPermissionsRequestAllPass()
    }

    open fun requestSpecPermissions(permissionList: Array<String>) {
        try {
            startEasyPermissions(
                getString(R.string.permission_tips),
                permissionList
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    protected fun startEasyPermissions(
        reqStatement: String,
        permissionList: Array<String>
    ) {
        mPermissionStatement = reqStatement
        mPermissionList = permissionList

        EasyPermissions.requestPermissions(
            this,
            reqStatement,
            REQ_GARLICLOAN_CODE_GARLICLOAN_PAGE_GARLICLOAN_PERMISSION,
            *permissionList
        )
    }

    open fun isAllFormDataCompleted(): String {
        return ""
    }


    /** 关联刷新 */
    open fun connectSwipeRefreshLayout(
        layout: SwipeRefreshLayout?,
        listener: SwipeRefreshLayout.OnRefreshListener
    ) {
        mSwipeRefresh = layout

        mSwipeRefresh?.apply {
            setColorSchemeColors(
                ContextCompat.getColor(
                    this@BaseActivity,
                    R.color.main_blue
                )
            )

            setOnRefreshListener(listener)
        }
    }

    /** 关闭刷新 */
    open fun stopRefreshState() {
        mSwipeRefresh?.isRefreshing = false
    }

    /** 打开刷新 */
    open fun startRefreshState() {
        mSwipeRefresh?.isRefreshing = true
    }
}